
local TankHealth = class("TankHealth", require("unity.LuaMonoBehaviour"))

---
---mStartingHealth number
---mSlider Slider
---mFillImage Image
---mFullHealthColor Color
---mZeroHealthColor Color
---mExplosionPrefab GameObject
---
function TankHealth:Awake()
    self.mExplosionAudio = nil
    self.mExplosionParticles = nil
    self.mCurrentHealth = 0
    self.mDead = false

    self.mExplosionParticles = UnityEngine.Object.Instantiate(self.mExplosionPrefab):GetComponent("ParticleSystem")
    self.mExplosionAudio = self.mExplosionParticles:GetComponent("AudioSource");
    self.mExplosionParticles.gameObject:SetActive (false)
end

function TankHealth:OnEnable()
    self.mCurrentHealth = self.mStartingHealth
    self.mDead = false
    self:SetHealthUI()
end

function TankHealth:SetHealthUI()
    self.mSlider.value = self.mCurrentHealth
    self.mFillImage.color = Color.Lerp (self.mZeroHealthColor, self.mFullHealthColor, self.mCurrentHealth / self.mStartingHealth)
end

function TankHealth:TakeDamage(amount)
    self.mCurrentHealth = self.mCurrentHealth - amount
    self:SetHealthUI()
    if self.mCurrentHealth <= 0 and not self.mDead then
        self:OnDeath ()
    end
end

function TankHealth:OnDeath()
    self.mDead = true
    self.mExplosionParticles.transform.position = self.transform.position
    self.mExplosionParticles.gameObject:SetActive (true)
    self.mExplosionParticles:Play ()
    self.mExplosionAudio:Play()
    self.gameObject:SetActive(false)
end

return TankHealth
